import { MutableRefObject, useEffect, useRef, useState } from 'react'
import './chat.scss'
import ChatItem from '../../component/chatItem/chatItem'
import ChatSearch from './search/search'
import Notice from '../../component/notice/notice'
import axios from '../../util/http'
import socket from '../../util/socket'
import { useLocation } from 'react-router-dom'
import { formatQuery } from '../../util/util'
type TChatItem = {
  UserId: number
  avatar: string
  id: number
  message: string
  realname: string
  time: string
  toUser: string
  type?: string
}
type TUserInfo = {
  avatar: string
  exp: string
  iat: string
  id: string
  realname: string
  status: string
  username: string
}
const Chat = () => {
  useEffect(() => {
    getChatList()
    listenSocket()
    initJoinRoom()
    scrollToBottom()
    return () => {
      leaveRoom()
    }
  }, [])

  const { search } = useLocation()

  const [test, setTest] = useState(0)
  const { username, realname, avatar, id: userId, toUser, token } = formatQuery(search.slice(1))
  console.log(userId)
  const [chatList, setChatList] = useState<Array<TChatItem>>([])
  const currentRoom = toUser ? toUser : username
  const chatDom: MutableRefObject<HTMLDivElement | null> = useRef(null)
  const scrollDom: MutableRefObject<HTMLDivElement | null> = useRef(null)
  useEffect(() => {
    scrollToBottom()
  }, [chatList])
  const scrollToBottom = () => {
    const elementHeight = scrollDom.current?.getBoundingClientRect().height!
    window.scrollTo(0, elementHeight)
  }
  const getChatList = () => {
    console.log(currentRoom)

    axios
      .get('/chat/search', {
        params: {
          username: currentRoom,
          Tousername: '2628735401'
        }
      })
      .then(res => {
        setChatList([...res.data.data])
      })
  }
  const sendMessage = (value: string) => {
    if (value.trim() === '') {
      return
    }
    axios
      .get('/chat/add', {
        params: {
          username,
          content: value,
          to: currentRoom
        },
        headers: {
          Authorization: `Bearer ${token}`
        }
      })
      .then(res => {
        res.data.error === -1 &&
          socket.emit('message', {
            msg: value,
            username: currentRoom,
            realname,
            avatar,
            id: parseInt(userId),
            roomType: 'single'
          })
      })
  }
  const leaveRoom = () => {
    socket.emit('leave', {
      username: currentRoom,
      realname: realname
    })
  }
  const listenSocket = () => {
    socket.on('message', (data: any) => {
      console.log(data)
      setChatList(preState => [...preState, data])
    })
  }
  const initJoinRoom = () => {
    socket.emit('online', {
      username: currentRoom,
      realname,
      roomType: 'single'
    })
  }

  return (
    <div className="chat" ref={chatDom}>
      <div ref={scrollDom}>
        {chatList.map((item, index) =>
          item.type !== 'notice' ? (
            <ChatItem
              message={item.message}
              direction={item.UserId * 1 !== parseInt(userId) ? 'left' : 'right'}
              imgSrc={item.avatar}
              realname={item.realname}
              key={index + ''}
            ></ChatItem>
          ) : (
            <Notice message={item.message} key={index + Math.random()}></Notice>
          )
        )}
        <ChatSearch sendMessage={sendMessage}></ChatSearch>
      </div>
    </div>
  )
}

export default Chat
